package com.pig4cloud.pig.admin.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pig4cloud.pig.admin.api.entity.MetaEntityEntity;
import com.pig4cloud.pig.admin.service.MetaEntityService;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.base.Group;
import com.pig4cloud.pig.common.security.annotation.HasPermission;
import com.pig4cloud.pig.common.security.annotation.Inner;
import com.pig4cloud.plugin.excel.annotation.RequestExcel;
import com.pig4cloud.plugin.excel.annotation.ResponseExcel;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.http.HttpHeaders;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

/**
 * 实体表
 *
 * @author pig
 * @date 2024-09-23 15:56:01
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/metaEntity")
@Tag(description = "metaEntity", name = "实体表管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class MetaEntityController {

	private final MetaEntityService metaEntityService;

	/**
	 * 分页查询
	 *
	 * @param page       分页对象
	 * @param metaEntity 实体表
	 * @return
	 */
	@Operation(summary = "分页查询", description = "分页查询")
	@GetMapping("/page")
	@HasPermission("admin_metaEntity_view")
	public R getMetaEntityPage(@ParameterObject Page page, @ParameterObject MetaEntityEntity metaEntity) {
		LambdaQueryWrapper<MetaEntityEntity> wrapper = Wrappers.lambdaQuery();
		wrapper.like(StrUtil.isNotBlank(metaEntity.getName()),MetaEntityEntity::getName,metaEntity.getName());
		wrapper.like(StrUtil.isNotBlank(metaEntity.getLabel()),MetaEntityEntity::getLabel,metaEntity.getLabel());
		wrapper.eq(Objects.nonNull(metaEntity.getType()),MetaEntityEntity::getType,metaEntity.getType());
		wrapper.eq(StrUtil.isNotBlank(metaEntity.getFlowStatus()),MetaEntityEntity::getFlowStatus,metaEntity.getFlowStatus());
		wrapper.eq(StrUtil.isNotBlank(metaEntity.getAutoStartFlow()),MetaEntityEntity::getAutoStartFlow,metaEntity.getAutoStartFlow());
        return R.ok(metaEntityService.page(page, wrapper));
	}

	/**
	 * 根据idList查询实体列表
	 *
	 * @param ids id列表
	 */
	@Inner
	@PostMapping("/queryListByFlowKeyList")
	public R getEntityByIds(@RequestBody List<String> flowKeyList) {
		if (ObjectUtil.isEmpty(flowKeyList)) {
			return R.ok(List.of());
		}
		return R.ok(metaEntityService.list(
				Wrappers.lambdaQuery(MetaEntityEntity.class).select(
						MetaEntityEntity::getFlowKey,
						MetaEntityEntity::getName,
						MetaEntityEntity::getId,
						MetaEntityEntity::getPhysicalName,
						MetaEntityEntity::getLabel,
						MetaEntityEntity::getFormJson
				).in(MetaEntityEntity::getFlowKey, flowKeyList)
		));
	}


	/**
	 * 通过条件查询实体表
	 *
	 * @param metaEntity 查询条件
	 * @return R  对象列表
	 */
	@Operation(summary = "通过条件查询", description = "通过条件查询对象")
	@GetMapping("/details")
	@HasPermission("admin_metaEntity_view")
	public R getDetails(@ParameterObject MetaEntityEntity metaEntity) {
		return R.ok(metaEntityService.list(Wrappers.query(metaEntity)));
	}

	/**
	 * 新增实体表
	 *
	 * @param metaEntity 实体表
	 * @return R
	 */
	@Operation(summary = "新增实体表", description = "新增实体表")
	@SysLog("新增实体表")
	@PostMapping
	@HasPermission("admin_metaEntity_add")
	public R save(@RequestBody @Valid MetaEntityEntity metaEntity) {
		return metaEntityService.saveMetaEntityEntity(metaEntity);
	}

	/**
	 * 修改实体表
	 *
	 * @param metaEntity 实体表
	 * @return R
	 */
	@Operation(summary = "修改实体表", description = "修改实体表")
	@SysLog("修改实体表")
	@PutMapping
	@HasPermission("admin_metaEntity_edit")
	public R updateById(@RequestBody @Valid MetaEntityEntity metaEntity) {
		metaEntity.setLabel(null);
		metaEntity.setPhysicalName(null);

		if (CommonConstants.YES.toString().equals(metaEntity.getFlowStatus())) {
			MetaEntityEntity metaEntityEntity = metaEntityService.getById(metaEntity.getId());
			if (Objects.isNull(metaEntityEntity)) {
				return R.failed("未查询到实体");
			}
			if (ObjectUtil.isNull(metaEntityEntity.getFlowKey())) {
				return R.failed("流程未配置，请先配置流程");
			}
		}

		if (CommonConstants.NO.toString().equals(metaEntity.getFlowStatus())) {
			metaEntity.setAutoStartFlow(CommonConstants.STATUS_NORMAL);
		}


		return R.ok(metaEntityService.updateById(metaEntity));
	}

	/**
	 * 通过id删除实体表
	 *
	 * @param ids id列表
	 * @return R
	 */
	@Operation(summary = "通过id删除实体表", description = "通过id删除实体表")
	@SysLog("通过id删除实体表")
	@DeleteMapping
	@HasPermission("admin_metaEntity_del")
	public R removeById(@RequestBody Long[] ids) {
		return R.ok(metaEntityService.removeMetaEntity(ids));
	}


	/**
	 * 导出excel 表格
	 *
	 * @param metaEntity 查询条件
	 * @param ids        导出指定ID
	 * @return excel 文件流
	 */
	@ResponseExcel
	@GetMapping("/export")
	@HasPermission("admin_metaEntity_export")
	public List<MetaEntityEntity> exportExcel(MetaEntityEntity metaEntity, Long[] ids) {
		return metaEntityService.list(Wrappers.lambdaQuery(metaEntity).in(ArrayUtil.isNotEmpty(ids), MetaEntityEntity::getId, ids));
	}

	/**
	 * 导入excel 表
	 *
	 * @param metaEntityList 对象实体列表
	 * @param bindingResult  错误信息列表
	 * @return ok fail
	 */
	@PostMapping("/import")
	@HasPermission("admin_metaEntity_export")
	public R importExcel(@RequestExcel List<MetaEntityEntity> metaEntityList, BindingResult bindingResult) {
		return R.ok(metaEntityService.saveBatch(metaEntityList));
	}

	/**
	 * 保存列显示
	 */
	@Operation(summary = "保存列显示", description = "保存列显示")
	@PutMapping("/saveShowField/{id}")
	public R saveShowField(@RequestBody List<String> metaFieldEntityList, @PathVariable String id) {
		return metaEntityService.saveShowField(id, metaFieldEntityList);
	}


	/**
	 * 保存列显示
	 */
	@Operation(summary = "保存列显示", description = "保存列显示")
	@PutMapping("/saveCondition/{id}")
	public R saveCondition(@RequestBody Group groupConditions, @PathVariable String id) {
		return metaEntityService.saveCondition(id, groupConditions);
	}

	/**
	 * 表单保存设计
	 */
	@Operation(summary = "表单保存设计", description = "表单保存设计")
	@PutMapping("/saveFormJson/{id}")
	public R saveFormJson(@RequestBody List<Map<String, Object>> formJson, @PathVariable String id) {
		return metaEntityService.saveFormJson(id, formJson);
	}

	/**
	 * 根据id获取表单设计
	 */
	@Operation(summary = "根据id获取表单设计", description = "根据id获取表单设计")
	@GetMapping("/getFormJson/{id}")
	public R getFormJson(@PathVariable String id) {
		return R.ok(Optional.ofNullable((metaEntityService.getById(id))).orElse(new MetaEntityEntity()).getFormJson());
	}

	/**
	 * 根据label获取表单设计
	 */
	@Operation(summary = "根据label获取表单设计", description = "根据label获取表单设计")
	@GetMapping("/getEntityByLabel/{label}")
	public R getEntityByLabel(@PathVariable String label) {
		return R.ok(Optional.ofNullable((metaEntityService.getOne(Wrappers.lambdaQuery(MetaEntityEntity.class).eq(MetaEntityEntity::getLabel, label)))).orElse(new MetaEntityEntity()));
	}

	/**
	 * 根据id获取流程字段
	 */
	@Operation(summary = "根据id获取流程字段", description = "根据id获取流程字段")
	@GetMapping("/getFlowField/{id}")
	public R getFlowField(@PathVariable String id) {
		return R.ok(metaEntityService.getFlowFieldById(id));
	}
}
